﻿using System;
using System.Collections.Generic;
using System.Text;
using He.Model;
using He.BLL;
using System.Configuration;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using He.Common;
using System.Collections;
using System.Xml;


namespace He.Web.UI
{
    /// <summary>
    /// 后台管理页面的父类
    /// </summary>
    public partial class Manage : PageBase
    {
        public Model.site_info siteinfo;           //网站信息
        public string lang;                        //语言版本
        public Manage()
        {
            lang = InputUtil.Get("lang", "cn");
            if (!string.IsNullOrEmpty(InputUtil.Get("lang")))
            {
                CookieHelper.Set(SysKeys.CURRENT_LANG_COOKIE_NAME, lang);
            }

            this.Load += new EventHandler(Manage_Load);
            siteinfo = new BLL.site_info().GetModelByLang(lang);
        }

        void Manage_Load(object sender, EventArgs e)
        {
            if (!IsAdminLogin())
            {
                Response.Write("<script>parent.location.href='" + webset.web_path + SysKeys.ADMIN_LOGIN_PAGE + "'</script>");
                Response.End();
            }
        }


        #region 后台分类操作

        /// <summary>
        /// 取得分类的最大级数
        /// </summary>
        /// <param name="channel"></param>
        /// <returns></returns>
        public int GetMaxLayerNumber(int channel_id)
        {
            He.BLL.channel bll = new BLL.channel();
            He.Model.channel model = bll.GetModel(channel_id);
            return model.max_layer;
        }

        public string echoAddSub(object layer, object category_id, int channel_id)
        {
            int max = GetMaxLayerNumber(channel_id);
            int currentlayer = Convert.ToInt16(layer);
            if (currentlayer >= max)
            {
                return string.Empty;
            }
            return string.Format("<span><a href='edit.aspx?channel_id={0}&parentId={1}'>添加子类</a></span> <span><a href='batch.aspx?channel_id={0}&parentId={1}'>批量添加子类</a></span>", channel_id, category_id);
        }

        public string echoAddSub2(object layer, object category_id, int channel_id)
        {
            int max = GetMaxLayerNumber(channel_id);
            int currentlayer = Convert.ToInt16(layer);
            if (currentlayer >= max)
            {
                return string.Empty;
            }
            return string.Format("<span><a href='category_edit.aspx?channel_id={0}&parentId={1}'>添加子类</a></span>", channel_id, category_id);
        }

        #endregion

        #region 返回广告位类型名称
        protected string GetTypeName(int type)
        {
            switch (type)
            {
                case 1:
                    return "文字";
                case 2:
                    return "图片";
                case 3:
                    return "幻灯片";
                case 4:
                    return "动画";
                case 5:
                    return "FLV视频";
                case 6:
                    return "代码";
                default:
                    return "其它";
            }
        }
        #endregion

        #region 下拉控件数据绑定
        /// <summary>
        /// 绑定类别DropDownList控件
        /// </summary>
        /// <param name="parentId">父类ID</param>
        /// /// <param name="firstItemTxt">第一项显示的文字</param>
        /// <param name="channel_id">大类ID</param>
        /// <param name="ddl">要绑定的DropDownList控件</param>
        protected void CategoryTreeBind(int parentId, string firstItemTxt, int channel_id, DropDownList ddl)
        {
            He.BLL.category channelMgr = new He.BLL.category();
            DataTable dt = channelMgr.GetList(parentId, channel_id);

            ddl.Items.Clear();
            ddl.Items.Add(new ListItem(firstItemTxt, ""));
            foreach (DataRow dr in dt.Rows)
            {
                string Id = dr["Id"].ToString();
                int layer = int.Parse(dr["layer"].ToString());
                string Title = dr["Title"].ToString().Trim();

                if (layer == 1)
                {
                    ddl.Items.Add(new ListItem(Title, Id));
                }
                else
                {
                    Title = "├ " + Title;
                    Title = StringHelper.Repeat("　", layer - 1) + Title;
                    ddl.Items.Add(new ListItem(Title, Id));
                }
            }
        }
        public string CategorySelectBind(int channel_id, object category_id, object id)
        {
            StringBuilder strTemp = new StringBuilder();
            He.BLL.category bll = new BLL.category();
            DataTable dt = bll.GetList(0, channel_id);
            if (dt.Rows.Count > 0)
            {
                strTemp.AppendFormat("<select class=\"select\" onchange=\"save_category(this,{0},{1})\">", channel_id, id);
                foreach (DataRow dr in dt.Rows)
                {
                    string txt;
                    int layer = Convert.ToInt32(dr["layer"]);
                    if (layer == 1)
                    {
                        txt = dr["title"].ToString();
                    }
                    else
                    {
                        txt = "├ " + dr["title"];
                        txt = StringHelper.Repeat("　", layer - 1) + txt;
                    }
                    strTemp.AppendFormat("<option value=\"{0}\"{1}>{2}</option>", dr["id"], dr["id"].ToString() == category_id.ToString() ? " selected=\"true\"" : "", txt);
                }
                strTemp.Append("</select>");
            }
            return strTemp.ToString();
        }
        #endregion

        #region 日志记录
        /// <summary>
        /// 日志写入方法
        /// </summary>
        /// <param name="str"></param>
        public void SaveLogs(string str)
        {
            if (webset.adminlogs_status == (int)Enums.Status.关闭)
            {
                return;
            }
            BLL.adminlogs bll = new BLL.adminlogs();
            Model.adminlogs model = new Model.adminlogs();
            if (Session["AdminName"] != null)
            {
                model.admin_name = Session["AdminName"].ToString();
                model.note = str;
                model.ip = HttpContext.Current.Request.UserHostAddress;
                model.add_time = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                bll.Add(model);
            }
            else
            {
                Response.Write("<script>parent.location.href='" + SysKeys.ADMIN_LOGIN_PAGE + "'</script>");
                Response.End();
            }
        }
        #endregion

        #region 后台JS提示

        public void ShowError(string msg)
        {
            JscriptPrint(msg, HttpContext.Current.Request.RawUrl, "Error");
        }
        public void ShowSuccess(string msg, string url)
        {
            JscriptPrint(msg, url, "Success");
        }
        public void ShowParamError()
        {
            JscriptMsg(350, 230, "错误提示", "<b>出现错误啦！</b>您要修改的信息不存在或参数不正确。", "back", "Error");
        }
        public void ShowParamError(string msg)
        {
            JscriptMsg(350, 230, "错误提示", string.Format("<b>出现错误啦！</b>{0}", msg), "back", "Error");
        }
        /// <summary>
        /// 遮罩提示窗口
        /// </summary>
        /// <param name="w">宽度</param>
        /// <param name="h">高度</param>
        /// <param name="msgtitle">窗口标题</param>
        /// <param name="msgbox">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="msgcss">CSS样式</param>
        protected void JscriptMsg(int w, int h, string msgtitle, string msgbox, string url, string msgcss)
        {
            string msbox = "";
            msbox += "<script type=\"text/javascript\">\n";
            msbox += "parent.jsmsg(" + w + "," + h + ",\"" + msgtitle + "\",\"" + msgbox + "\",\"" + url + "\",\"" + msgcss + "\")\n";
            msbox += "</script>\n";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsMsg", msbox);
        }

        /// <summary>
        /// 添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="msgcss">CSS样式</param>
        protected void JscriptPrint(string msgtitle, string url, string msgcss)
        {
            string msbox = "";
            msbox += "<script type=\"text/javascript\">\n";
            msbox += "parent.jsprint(\"" + msgtitle + "\",\"" + url + "\",\"" + msgcss + "\")\n";
            msbox += "</script>\n";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox);
        }
        #endregion

        #region 后台管理员操作

        /// <summary>
        /// 判断用户权限
        /// </summary>
        protected void chkLoginLevel(string pagestr)
        {
            string msbox = "";
            int utype = int.Parse(Session["AdminType"].ToString());
            string ulevel = Session["AdminLevel"].ToString();
            if (utype > (int)Enums.AdminType.超级管理员)
            {
                pagestr += ",";
                if (ulevel.IndexOf(pagestr) == -1)
                {
                    msbox += "<script type=\"text/javascript\">\n";
                    msbox += "parent.jsmsg(350,230,\"警告提示\",\"<b>没有管理权限</b>您没有权限管理该功能，请勿非法进入。\",\"back\")\n";
                    msbox += "</script>\n";
                    Response.Write(msbox);
                    Response.End();
                }
            }
        }

        /// <summary>
        /// 判断管理员是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsAdminLogin()
        {
            //如果Session为Null
            if (Session["AdminNo"] != null && Session["AdminName"] != null && Session["AdminLevel"] != null && Session["AdminType"] != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = CookieHelper.Get("AdminName");
                string adminpwd = CookieHelper.Get("AdminPwd");
                if (adminname != "" && adminpwd != "")
                {
                    adminname = CryptoHelper.DESDecrypt(adminname); //解密用户名
                    He.BLL.administrator bll = new He.BLL.administrator();
                    if (bll.chkAdminLogin(adminname, adminpwd))
                    {
                        He.Model.administrator model = new He.Model.administrator();
                        model = bll.GetModel(adminname);
                        Session["AdminNo"] = model.id;
                        Session["AdminName"] = model.user_name;
                        Session["AdminType"] = model.user_type;
                        Session["AdminLevel"] = model.user_level;
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 获取管理员类型
        /// </summary>
        /// <param name="user_type"></param>
        /// <returns></returns>
        public string GetAdminType(object admin_type)
        {
            int type = Convert.ToInt32(admin_type);
            return EnumHelper.GetEnumVal(type, typeof(Enums.AdminType));
        }

        #endregion

        #region XML文件操作
        /// <summary>
        /// 将营销网络以XML格式输出到Mapdata.asp
        /// </summary>
        public void WriteNetworkXml()
        {
            //Mapdata.asp
            try
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("<?xml version='1.0' encoding='utf-8'?>");
                sb.Append("\r\n");
                sb.Append("<data>" + "\r\n");
                sb.Append("<web>" + "\r\n");

                DataSet ds = new BLL.network().GetList(string.Format(" is_show=1 and lang='{0}' ", lang));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        sb.Append("\r\n");
                        sb.Append("<project name=\"" + Convert.ToString(dr["Title"]) + "\" Province=\"" + Convert.ToString(dr["Province"]) + "\">" + "\r\n");
                        sb.Append(Convert.ToString(dr["Content"]) + "</project>" + "\r\n");
                    }
                }
                sb.Append("</web>" + "\r\n");
                sb.Append("</data>");

                string savePath = "";
                List<Model.Lang> lst = new He.BLL.config().LoadConfig<List<Model.Lang>>(LangXmlPath);
                foreach (Model.Lang item in lst)
                {
                    if (item.Value == lang)
                    {
                        savePath = Server.MapPath(string.Format("~/{0}mapdata.asp", lang == "cn" ? "" : lang + "/"));
                    }
                }

                System.IO.StreamWriter sw = System.IO.File.CreateText(savePath);
                sw.Write(sb.ToString());
                sw.Close();

            }
            catch (Exception e)
            {
                System.IO.StreamWriter sw1 = System.IO.File.AppendText(System.IO.Directory.GetCurrentDirectory() + "log.txt");
                sw1.WriteLine(System.DateTime.Now + " : " + e.Message);
                sw1.Close();
            }
        }
        /// <summary>
        /// 将轮播图片以XML形式输出到config.xml
        /// </summary>
        public void WriteCu3erXml(int position_id)
        {
            string[] trans = new string[10];
            trans[0] = "<transition direction=\"left\"/>";
            trans[1] = "<transition duration=\"0.6\" delay=\".2\" direction=\"down\"/>";
            trans[2] = "<transition num=\"3\" slicing=\"horizontal\" direction=\"left\" delay=\"0.05\"/>";
            trans[3] = "<transition num=\"3\"/>";
            trans[4] = "<transition  num=\"6\" slicing=\"horizontal\"  direction=\"right\" duration=\"0.8\"  delay=\"0.05\" z_multiplier=\"5\"/>";
            trans[5] = "<transition num=\"6\" slicing=\"vertical\" direction=\"down\" shader=\"phong\" delay=\"0.05\"/>";
            trans[6] = "<transition num=\"4\" direction=\"down\" slicing=\"horizontal\" z_multiplier=\"6\" delay=\"0.1\"/>";
            trans[7] = "<transition num=\"4\" direction=\"up\" z_multiplier=\"2.5\" delay=\"0.03\"/>";
            trans[8] = "<transition direction=\"right\"/>";
            trans[9] = "<transition num=\"3\" direction=\"up\"/>";
            Random r = new Random();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml version='1.0' encoding='utf-8'?>");
                sb.Append("\r\n");
                sb.Append("<data>" + "\r\n");
                sb.Append("<settings>" + "\r\n");
                sb.Append("<auto_play>" + "\r\n");
                sb.Append("<defaults symbol=\"circular\" />" + "\r\n");
                sb.Append("<tweenIn x=\"795\" y=\"45\" width=\"30\" height=\"30\" tint=\"0xF4BC21\" alpha=\"0.5\"/>" + "\r\n");
                sb.Append("<tweenOver alpha=\"1\"/>" + "\r\n");
                sb.Append("</auto_play>" + "\r\n");
                sb.Append("<prev_button>" + "\r\n");
                sb.Append("<tweenIn x=\"765\" y=\"240\" width=\"30\" height=\"30\" alpha=\"0\" />" + "\r\n");
                sb.Append("</prev_button>" + "\r\n");
                sb.Append("<next_button>" + "\r\n");
                sb.Append("<tweenIn x=\"795\" y=\"240\" width=\"30\" height=\"30\" alpha=\"0\" />" + "\r\n");
                sb.Append("<tweenOver alpha=\"0\" />" + "\r\n");
                sb.Append("</next_button>" + "\r\n");
                sb.Append("<prev_symbol>" + "\r\n");
                sb.Append("<defaults type=\"3\" />" + "\r\n");
                sb.Append("<tweenIn x=\"765\" y=\"240\" alpha=\"0.5\"  />" + "\r\n");
                sb.Append("<tweenOver time=\"0.15\" x=\"760\" scaleX=\"1.1\" scaleY=\"1.1\" />" + "\r\n");
                sb.Append("</prev_symbol>" + "\r\n");
                sb.Append("<next_symbol>" + "\r\n");
                sb.Append("<defaults type=\"3\" />" + "\r\n");
                sb.Append("<tweenIn x=\"795\" y=\"240\" alpha=\"0.5\"/>" + "\r\n");
                sb.Append("<tweenOver time=\"0.15\" x=\"800\" scaleX=\"1.1\" scaleY=\"1.1\" />" + "\r\n");
                sb.Append("</next_symbol>" + "\r\n");
                sb.Append("<description>" + "\r\n");
                sb.Append("<defaults round_corners=\"10, 10, 10, 10\" heading_text_size=\"22\" heading_text_color=\"0xfc9900\" paragraph_text_size=\"13\" paragraph_text_color=\"0xF4BC21\" />" + "\r\n");
                sb.Append("<tweenIn x=\"200\" y=\"240\" width=\"560\" height=\"90\" alpha=\"0.15\" />" + "\r\n");
                sb.Append("<tweenOver alpha=\"0.3\"/>" + "\r\n");
                sb.Append("</description>" + "\r\n");
                sb.Append("<transitions slicing=\"vertical\"  direction=\"down\" duration=\"0.6\"  delay=\"0.2\" cube_color=\"0x611811\" />" + "\r\n");
                sb.Append("</settings>" + "\r\n");
                sb.Append("<slides>" + "\r\n");

                string xmlFilePath = "";
                List<Model.Lang> lst = new He.BLL.config().LoadConfig<List<Model.Lang>>(LangXmlPath);
                foreach (Model.Lang item in lst)
                {
                    if (item.Value == lang)
                    {
                        xmlFilePath = Server.MapPath(string.Format("~/{0}config.xml", lang == "cn" ? "" : lang + "/"));
                    }
                }

                DataSet ds = new BLL.ad().GetList(string.Format("is_red=1 and position_id={0} order by sort_id asc,id desc", position_id));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    int i = 0;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        sb.Append("<slide>" + "\r\n");
                        sb.Append("<url>" + dr["img_url"].ToString() + "</url>" + "\r\n");
                        sb.Append("<link>" + dr["link_url"].ToString() + "</link>" + "\r\n");
                        sb.Append("</slide>" + "\r\n");
                        sb.Append(trans[i] + "\r\n");
                        i++;
                    }
                }
                sb.Append("</slides>" + "\r\n");
                sb.Append("</data>");
                System.IO.StreamWriter sw = new StreamWriter(xmlFilePath, false, Encoding.UTF8);
                sw.Write(sb.ToString());
                sw.Close();
            }
            catch (Exception e)
            {
                System.IO.StreamWriter sw1 = System.IO.File.AppendText(System.IO.Directory.GetCurrentDirectory() + "log.txt");
                sw1.WriteLine(System.DateTime.Now + " : " + e.Message);
                sw1.Close();
            }

        }
        #endregion

        #region 组合SQL语句

        /// <summary>
        /// 组合SQL查询语句
        /// </summary>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            strTemp.Append("id>0");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        /// <summary>
        /// 组合SQL查询语句
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <returns></returns>
        protected string CombSqlTxt(int _channel_id)
        {
            StringBuilder strTemp = new StringBuilder();
            strTemp.Append("Id>0 ");
            if (_channel_id > 0)
            {
                strTemp.Append("and category_id in(select Id from he_category where channel_id=" + _channel_id + ")");
            }
            return strTemp.ToString();
        }
        /// <summary>
        /// 组合SQL查询语句（用于会员）
        /// </summary>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombMemberSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            strTemp.Append("id>0");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and user_name like '%" + _keywords + "%' or nickname like '%" + _keywords + "%'");
            }
            return strTemp.ToString();
        }
        /// <summary>
        /// 查询语句
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <param name="_category_id">类别ID</param>
        /// <returns></returns>
        protected string CombSqlTxt(int _channel_id, int _category_id)
        {
            StringBuilder strTemp = new StringBuilder();
            string kindSql = " category_id in(select Id from he_category where channel_id=" + _channel_id + ")";
            strTemp.Append("Id>0 and " + kindSql);
            if (_category_id > 0)
            {
                strTemp.Append(" and category_id in(select Id from he_category where id_list like '%," + _category_id + ",%')");
            }
            return strTemp.ToString();
        }

        /// <summary>
        /// 组合SQL查询语句
        /// </summary>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombSqlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            strTemp.Append("Id>0");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and Title like '%" + _keywords + "%'");
            }

            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isLock":
                        strTemp.Append(" and IsLock=1");
                        break;
                    case "unIsLock":
                        strTemp.Append(" and IsLock=0");
                        break;
                    case "isMsg":
                        strTemp.Append(" and IsMsg=1");
                        break;
                    case "isTop":
                        strTemp.Append(" and IsTop=1");
                        break;
                    case "isRed":
                        strTemp.Append(" and IsRed=1");
                        break;
                    case "isHot":
                        strTemp.Append(" and IsHot=1");
                        break;
                    case "isSlide":
                        strTemp.Append(" and IsSlide=1");
                        break;
                }
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 组合SQL查询语句
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombSqlTxt(int _channel_id, int _category_id, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (_category_id > 0)
            {
                strTemp.Append(" and category_id in(select Id from he_category where channel_id=" + _channel_id + " and id_list like '%," + _category_id + ",%')");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and Title like '%" + _keywords + "%'");
            }

            return strTemp.ToString();
        }
        /// <summary>
        /// 组合SQL查询语句
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombSqlTxt(int _channel_id, int _category_id, string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            string kindSql = string.Format(" category_id in(select id from {0}category where channel_id={1})", SysKeys.TABLE_PREFIX, _channel_id);
            strTemp.Append("id>0 and " + kindSql);
            if (_category_id > 0)
            {
                strTemp.Append(" and category_id in(select Id from he_category where id_list like '%," + _category_id + ",%')");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isLock":
                        strTemp.Append(" and is_lock=1");
                        break;
                    case "unIsLock":
                        strTemp.Append(" and is_lock=0");
                        break;
                    case "isMsg":
                        strTemp.Append(" and is_msg=1");
                        break;
                    case "isTop":
                        strTemp.Append(" and is_top=1");
                        break;
                    case "isRed":
                        strTemp.Append(" and is_red=1");
                        break;
                    case "isHot":
                        strTemp.Append(" and is_hot=1");
                        break;
                    case "isImg":
                        strTemp.Append(" and is_img=1");
                        break;
                }
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_pos_mark"></param>
        /// <param name="_lang"></param>
        /// <returns></returns>
        public string CombPlugSqlTxt(string _pos_mark, string _lang)
        {
            return string.Format("pos_mark='{0}' and lang='{1}'", _pos_mark, _lang);
        }

        /// <summary>
        /// 组合SQL查询语句(用于评论)
        /// </summary>
        /// <param name="_channel_id">栏目ID</param>
        /// <param name="_parentId">信息ID</param>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombPlSqlTxt(int _channel_id, int _parentId, string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (_channel_id >= 0)
            {
                strTemp.Append(" and channel_id=" + _channel_id);
            }
            if (_parentId > 0)
            {
                strTemp.Append(" and ParentId=" + _parentId);
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and (UserName like '%" + _keywords + "%' or Content like '%" + _keywords + "%')");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                switch (_property)
                {
                    case "isLock":
                        strTemp.Append(" and IsLock=1");
                        break;
                    case "unIsLock":
                        strTemp.Append(" and IsLock=0");
                        break;
                }
            }

            return strTemp.ToString();
        }

        /// <summary>
        ///  组合SQL查询语句(用于广告)
        /// </summary>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombAdSqlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and title like '%" + _keywords + "%'");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                strTemp.Append(" and ad_type=" + _property);
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 组合SQL查询语句(用于广告)
        /// </summary>
        /// <param name="_pid">广告位ID</param>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombAdSqlTxt(int _pid, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append(" and Title like '%" + _keywords + "%'");
            }
            if (_pid > 0)
            {
                strTemp.Append(" and Aid=" + _pid);
            }

            return strTemp.ToString();
        }




        #endregion

        #region 组合URL语句

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombUrlTxt(int _category_id, string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (_category_id > 0)
            {
                strTemp.Append("category_id=" + _category_id.ToString() + "&");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpContext.Current.Server.UrlEncode(_keywords) + "&");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                strTemp.Append("property=" + _property + "&");
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombUrlTxt(int _channel_id, int _category_id, string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (_channel_id >= 0)
            {
                strTemp.Append("channel_id=" + _channel_id.ToString() + "&");
            }
            if (_category_id > 0)
            {
                strTemp.Append("category_id=" + _category_id.ToString() + "&");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpContext.Current.Server.UrlEncode(_keywords) + "&");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                strTemp.Append("property=" + _property + "&");
            }

            return strTemp.ToString();
        }


        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_category_id">类别ID</param>
        /// <returns></returns>
        protected string CombUrlTxt(int _category_id)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_category_id > 0)
            {
                strTemp.Append("category_id=" + _category_id.ToString() + "&");
            }
            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_category_id">类别ID</param>
        /// <returns></returns>
        protected string CombContentsUrlTxt(int _channel_id)
        {
            StringBuilder strTemp = new StringBuilder();
            strTemp.Append("channel_id=" + _channel_id.ToString() + "&");
            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_category_id">类别ID</param>
        /// <returns></returns>
        protected string CombUrlTxt(int _channel_id, int _category_id)
        {
            StringBuilder strTemp = new StringBuilder();

            strTemp.Append("channel_id=" + _channel_id + "&");

            if (_category_id > 0)
            {
                strTemp.Append("category_id=" + _category_id.ToString() + "&");
            }
            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombUrlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpContext.Current.Server.UrlEncode(_keywords) + "&");
            }
            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_category_id">类别ID</param>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombUrlTxt(int _category_id, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            if (_category_id > 0)
            {
                strTemp.Append("category_id=" + _category_id.ToString() + "&");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpContext.Current.Server.UrlEncode(_keywords) + "&");
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句
        /// </summary>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombUrlTxt(string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpUtility.UrlEncode(_keywords) + "&");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                strTemp.Append("property=" + _property + "&");
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_keywords"></param>
        /// <param name="_property"></param>
        /// <returns></returns>
        protected string CombPlugUrlTxt(string _pos_mark, string _lang)
        {
            StringBuilder strTemp = new StringBuilder();
            if (!string.IsNullOrEmpty(_pos_mark))
            {
                strTemp.Append("pos_mark=" + _pos_mark + "&");
            }
            if (!string.IsNullOrEmpty(_lang))
            {
                strTemp.Append("lang=" + _lang + "&");
            }
            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句(用于评论)
        /// </summary>
        /// <param name="_channel_id">大类ID</param>
        /// <param name="_parentId">信息ID</param>
        /// <param name="_keywords">关健字</param>
        /// <param name="_property">属性</param>
        /// <returns></returns>
        protected string CombReviewsUrlTxt(int _channel_id, int _parentId, string _keywords, string _property)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (_channel_id >= 0)
            {
                strTemp.Append("channel_id=" + _channel_id.ToString() + "&");
            }
            if (_parentId > 0)
            {
                strTemp.Append("parentId=" + _parentId.ToString() + "&");
            }
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpContext.Current.Server.UrlEncode(_keywords) + "&");
            }
            if (!string.IsNullOrEmpty(_property))
            {
                strTemp.Append("property=" + _property + "&");
            }

            return strTemp.ToString();
        }

        /// <summary>
        /// 组合URL语句(用于广告)
        /// </summary>
        /// <param name="_pid">广告位ID</param>
        /// <param name="_keywords">关健字</param>
        /// <returns></returns>
        protected string CombAdUrlTxt(int _pid, string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                strTemp.Append("keywords=" + HttpUtility.UrlEncode(_keywords) + "&");
            }
            if (_pid > 0)
            {
                strTemp.Append("Pid=" + _pid + "&");
            }

            return strTemp.ToString();
        }


        #endregion

        #region 缓存操作
        public void RemoveAllCache()
        {
            List<Model.channel> sys_list = new BLL.channel().GetModelList("is_lock=0");
            foreach (Model.channel model in sys_list)
            {
                CacheHelper.Remove("channel_" + model.id);
                CacheHelper.Remove("channel_" + model.name);
            }
        }
        public void RemoveAdCache(string call_mark)
        {
            CacheHelper.Remove("ad_position_" + call_mark);
        }
        #endregion

        #region 水印状态
        public string getwatertype()
        {
            switch (webset.watermarktype)
            {
                case 0:
                    return "关闭水印";
                case 1:
                    return "文字水印";
                case 2:
                    return "图片水印";
                default:
                    return "状态错误，请联系技术人员";
            }
        }
        #endregion

        #region HTML操作
        /// <summary>
        /// 输出是否显示图片预览的样式
        /// </summary>
        /// <returns></returns>
        public string ShowReview(string imgUrl)
        {
            if (string.IsNullOrEmpty(imgUrl))
            {
                return "style='display:none;'";
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region G宝盆操作

        public bool AllowTongbu(Model.channel channel)
        {
            return ((channel.lang == "cn") && (webset.mobile_url.Length > 8));
        }

        public void Tongbu(Repeater rptList, Model.channel channel)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((Label)rptList.Items[i].FindControl("lb_id")).Text);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("cb_id");
                if (cb.Checked)
                {
                    sb.Append(id);
                    sb.Append(",");
                }
            }
            string ids = sb.ToString().Trim(new char[] { ',' });
            if (!string.IsNullOrEmpty(ids))
            {
                string condition = string.Format("id in ({0})", ids);
                string rs = this.GbpenTongbu(channel, condition, "update");

                if (rs == "true")
                {
                    this.ShowSuccess("操作成功啦！", base.Request.RawUrl);
                }
                else
                {
                    this.ShowError(rs);
                }
            }
            else
            {
                this.ShowError("没有选中项！");
            }
        }

        public string GbpenTongbu(Model.channel channel, string condition, string action)
        {
            this.GbpenTongbuXml(channel, condition, action);
            if (!webset.mobile_url.StartsWith("http://"))
            {
                webset.mobile_url = "http://" + webset.mobile_url;
            }
            webset.mobile_url = webset.mobile_url.Trim(new char[] { '/' }) + "/receive.php";
            return RemoteHelper.GetRemoteHtml(webset.mobile_url, Encoding.GetEncoding("gbk"));
        }
        public void GbpenTongbuXml(Model.channel channel, string condition, string action)
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "gbk", null);
            doc.AppendChild(dec);
            XmlNode mainNode = doc.CreateElement("main");
            List<Model.article> artList = new BLL.article().GetModelList(condition);
            foreach (Model.article item in artList)
            {
                XmlNode proNode = doc.CreateElement("pro");
                this.CreateNode(doc, proNode, "id", item.id.ToString());
                this.CreateNode(doc, proNode, "action", action);
                this.CreateNode(doc, proNode, "updatetime", string.Format("{0:yyyy-MM-dd hh:mm:ss}", DateTime.Now));
                this.CreateNode(doc, proNode, "sort", item.sort_id.ToString());
                this.CreateNode(doc, proNode, "title", item.title);
                this.CreateNode(doc, proNode, "description", item.seo_desc);
                this.CreateNode(doc, proNode, "imagesurl", item.img_url);
                XmlNode contentNode = doc.CreateElement("content");
                contentNode.AppendChild(doc.CreateCDataSection(item.content));
                proNode.AppendChild(contentNode);
                this.CreateNode(doc, proNode, "module", channel.title);
                this.CreateNode(doc, proNode, "show", "false");
                mainNode.AppendChild(proNode);
            }
            doc.AppendChild(mainNode);
            doc.Save(base.Server.MapPath("~/synchro.xml"));
        }
        public void CreateNode(XmlDocument doc, XmlNode proNode, string tagName, string tagVal)
        {
            XmlNode node = doc.CreateElement(tagName);
            node.AppendChild(doc.CreateTextNode(tagVal));
            proNode.AppendChild(node);
        }
        #endregion

        #region 产品相关操作
        /// <summary>
        /// 取得详细页展示效果
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> GetShowEffectDict(int model_id)
        {
            List<Model.show_effect> lst = new He.BLL.config().LoadConfig<List<Model.show_effect>>("~/config/show_effect.config");
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (Model.show_effect item in lst)
            {
                dict.Add(item.value, item.name);
            }
            return dict;
        }
        #endregion

        #region 微信相关操作
        public bool ExistsKeyword(string keyword, int thisId)
        {
            BLL.article bll = new BLL.article();
            if (!string.IsNullOrEmpty(keyword.Trim()))
            {
                if (bll.ExistsKeyword(keyword, thisId))
                {
                    return true;
                }
            }
            return false;
        }

        public void AddWxKeyword(int articleId, string keyword)
        {
            BLL.wx_keyword bll = new BLL.wx_keyword();
            if (!string.IsNullOrEmpty(keyword))
            {
                if (bll.ExistsByArticleId(articleId))
                {
                    Model.wx_keyword model = bll.GetModelByArticleId(articleId);
                    model.keyword = keyword;
                    bll.Update(model);
                }
                else
                {
                    Model.wx_keyword model = new Model.wx_keyword();
                    model.keyword = keyword;
                    model.article_id = articleId.ToString();
                    model.sort_id = 0;
                    model.msg_type = He.API.WeiXin.Enums.MsgType.news.ToString();
                    bll.Add(model);
                }
            }
            else
            {
                bll.DeleteByArticleId(articleId);
            }
        }

        public string GetWxKeyword(int articleId)
        {
            BLL.wx_keyword bll = new BLL.wx_keyword();
            if (bll.ExistsByArticleId(articleId))
            {
                Model.wx_keyword model = bll.GetModelByArticleId(articleId);
                return model.keyword;
            }
            return string.Empty;
        }

        public string GetWxMsgType(string msgType)
        {
            switch (msgType)
            {
                case "text":
                    return "纯文本";
                case "news":
                    return "文章";
            }
            return "";
        }

        public string GetWxAnswer(int id)
        {
            BLL.wx_keyword bll = new BLL.wx_keyword();
            BLL.article abll = new BLL.article();
            Model.wx_keyword model = bll.GetModel(id);
            StringBuilder strTemp = new StringBuilder();
            switch (model.msg_type)
            {
                case "text":
                    strTemp.Append(model.answer);
                    break;
                case "news":
                    string[] idArr = model.article_id.Split(',');
                    if (idArr.Length > 0)
                    {
                        foreach (string s in idArr)
                        {
                            int aid = Convert.ToInt32(s);
                            if (abll.Exists(aid))
                            {
                                Model.article article = abll.GetModel(aid);
                                strTemp.AppendFormat("<li id=\"row{1}\" style=\"height:60px;\"><img src=\"{2}\" width=\"50\" height=\"50\">{0} <a href=\"javascript:void(0)\" onclick=\"delRow({1})\">删除</a></li>", article.title, article.id, article.img_url);
                            }
                        }
                    }
                    break;
            }
            return strTemp.ToString();
        }
        #endregion
    }
}
